# 锐捷校园网登录
# python环境：3.10.10
# 1.获取当前网页认证url，提取里面的wlanip等各种数据
# 2.输入得用户名和密码+提取的进行登录

import os
import requests

username = '2222'  # input("请输入账号")
password = '2222'  # input("请输入密码")
url1 = "http://10.0.11.5/eportal/InterFace.do?method=login"  # 认证登录url
url2 = 'http://10.0.11.5/eportal/InterFace.do?method=getOnlineUserInfo'  # 获取当前用户信息


def check_ruijie():  # 判断是否连接校园网
    eportal_url = "10.0.11.5"  # 学校认证网关ip
    res = os.system(f"ping {eportal_url} -n 3")
    if res == 0:
        return True
    else:
        return False


def check_connection():  # 能否连接互联网
    res = os.system(f"ping www.baidu.com -n 3")
    if res == 0:
        return True
    else:
        return False


def get_userIndex(user, pwd):  # 账号、密码
    test_url = "http://www.baidu.com"  # 必须是http才会跳转出认证页
    resp = requests.get(test_url, verify=False)  # requests.exceptions.SSLError
    info = resp.text
    # 提取当前校园网认证网页url wlan的信息
    wlan_info = info.rsplit("\'")[1].rsplit("?", 1)[1]

    data = {
        "method": "login",
        "userId": f"{user}",
        "password": f"{pwd}",
        "service": "",
        "queryString": f"{wlan_info}",
        "operatorPwd": "",
        "operatorUserId": "",
        "validcode": "",
        "passwordEncrypt": "false"
    }
    resp = requests.post(url1, data)
    userIndex = resp.json()['userIndex']
    if userIndex:
        print("链接成功！")
    else:
        print("链接失败，请检查账号密码或校园网连接情况！")
        exit()
    return userIndex


def login_user_index():  # 认证登录后获取userIndex
    url = 'http://10.0.11.5/'
    resp = requests.get(url)
    res = resp.url.split("=", 1)[1]
    return res


def login(user_index):
    data = {
        "method": "getOnlineUserInfo",
        "userIndex": f"{user_index}"
    }
    # first request
    requests.post(url2, data=data)

    # the second requests
    resp2 = requests.post(url2, data=data)
    resp2.encoding = "utf-8"
    inf = resp2.json()

    name = inf["userName"]
    id = inf["userId"]
    ip = inf["userIp"]
    mac = inf["userMac"]
    typ = inf["userPackage"]
    print(f'{name} 你好，欢迎使用Python校园网自动登录！', f'\n用户：{id} \nip:{ip}\n', f'mac:{mac}\n', typ)


def down_internet(user_index):
    url = 'http://10.0.11.5/eportal/InterFace.do?method=logout'
    data = {
        "method": "logout",
        "userIndex": user_index
    }
    resp = requests.post(url, data=data)
    resp.encoding = "utf-8"
    if resp.status_code == 200:
        print("下线成功！")
    else:
        print("下线失败，请再试一下！")


def connection():
    if check_connection():  # 检查联网情况
        if check_ruijie():
            print("你当前已经连接校园网喽，有网心不慌!\n")
            shu = input("是否下线？（y/n）")
            if shu == 'y' or shu == 'Y':
                down_internet(login_user_index())
            else:
                print("床前明月光,有网心不慌~~")
        else:
            print("你当前已经联网啦，emmmm但貌似不是校园网，请重新连接哦")
    else:  # 如果没联网
        if check_ruijie():
            login(get_userIndex(username, password))
        else:
            print("请先接入校园网哦~")


if __name__ == '__main__':
    connection()
